import requests
import traceback
import json

from conf.settings import MONITOR_API
from utility.log import Logger

logger = Logger().get_logger()


class Monitor(object):
    def __init__(self):
        self._base_url = MONITOR_API['base_url']
        self._headers = {'Cookie': f"token={MONITOR_API['token']}"}

    def _ajax(self, method, url, params):
        try:
            params['token'] = MONITOR_API['token']
            send_url = f'{self._base_url}{url}'
            if method == 'GET':
                resp = requests.get(f'{send_url}', params=params, headers=self._headers, verify=False)
            else:
                resp = requests.post(f'{send_url}', json=params, headers=self._headers, verify=False)

            if resp.status_code != 200:
                logger.error(f"failed '{method}' url '{url}' to service, data: {params}, "
                             f"msg: {json.loads(resp.text)}")

            return resp
        except Exception as e:
            traceback.print_exc()
            logger.error(f"{e}, url: {url}, method: {method}, params: {params}")

            return {}

    def get(self, url, params):
        return self._ajax('GET', url, params)

    def post(self, url, params):
        return self._ajax('POST', url, params)
